<template>
  <div class="trad-box quotebg radius-8 parent">
    <div class="over-tab flex align-center js-sp share-color">
      <svg-icon
        @click="tabsClickScroll('left')"
        data-_icon-name="ic_trading_left"
        class="text-20 point"
        :class="scrollCount > 0 ? 'share' : 'text-secondary'"
      ></svg-icon>
      <svg-icon
        @click="tabsClickScroll('right')"
        data-_icon-name="ic_trading_right"
        class="text-20 point"
        :class="isShowRight ? 'share' : 'text-secondary'"
      ></svg-icon>
    </div>
    <div class="pd-hr-30">
      <div
        class="trad-tabbox flex js-st point text-bold quotet3 text-12 quoteline "
        ref="tabsRef"
      >
        <div
          v-for="(item, index) in state.tabList"
          :key="item.id"
          v-show="
            item.id === 3
              ? metaverse.lever
              : item.id === 4
              ? NFTtype.lever
              : true
          "
          class="trad-tab"
          @click="changeTab(item.id, index)"
          :class="{ 'active-line text-bolder quotet2': tabActive === item.id }"
        >
          {{ item.name }}
        </div>
      </div>
    </div>
    <div class="box">
      <!-- 搜索筐 -->
      <div class="search mb-20 quoteinput">
        <el-input
          v-model="state.curencyname"
          :placeholder="$t('exchange.inquire')"
          v-on:keyup.enter="search"
        >
          <template #prefix>
            <img
              style="width:16px;margin-top: 12px;display: block;"
              @click="search"
              src="@/assets/theme1/search.png"
              alt
            />
          </template>
        </el-input>
      </div>
      <!-- 升降序 -->
      <ul class="sort quotet3 text-12 flex js-sp align-start">
        <li class="text-left flex js-st flex-grow-1">
          {{ $t("exchange.lever") }}
          <!-- <div class="sort-icon flex flex-column">
            <i class="el-icon-caret-top text-12"></i>
            <i class="el-icon-caret-bottom text-12 personlink"></i>
          </div> -->
        </li>
        <li class="text-right flex js-ed w-33 ">
          {{ $t("deal.newprice") }}
          <div class="sort-icon flex flex-column">
            <i
              class="el-icon-caret-top text-12"
              @click="changeSort('close_price', 'asc')"
              :class="{ personlink: state.sortParam.close_price === 'asc' }"
            ></i>
            <i
              class="el-icon-caret-bottom text-12"
              @click="changeSort('close_price', 'desc')"
              :class="{ personlink: state.sortParam.close_price === 'desc' }"
            ></i>
          </div>
        </li>
        <li class="flex js-ed text-right w-25">
          {{ $t("exchange.24HChange") }}
          <div class="sort-icon flex flex-column">
            <i
              class="el-icon-caret-top text-12"
              @click="changeSort('increase', 'asc')"
              :class="{
                personlink: state.sortParam.increase === 'asc',
              }"
            ></i>
            <i
              class="el-icon-caret-bottom text-12"
              @click="changeSort('increase', 'desc')"
              :class="{
                personlink: state.sortParam.increase === 'desc',
              }"
            ></i>
          </div>
        </li>
      </ul>
    </div>
    <div class="trad-all customer-scroll" v-loading="state.loading">
      <div
        class="trad flex align-center point"
        v-for="(item, index) in state.tradList"
        @click="changeTrading(item)"
        :class="{
          'trading-active': $store.state.exchange.second_data.id === item.id,
        }"
        :key="index"
      >
        <div class="mb-6 flex-grow-1 text-left family-d flex align-center">
          <svg-icon
            class="text-20 mr-5"
            data-_icon-name="ic_icon_star_off"
            @click.stop="changeadd(item.id, item.is_user_currency_match)"
            v-if="!item.is_user_currency_match"
          ></svg-icon>
          <svg-icon
            class="text-20 mr-5"
            data-_icon-name="ic_icon_star_on"
            @click.stop="changeadd(item.id, item.is_user_currency_match)"
            v-else
          ></svg-icon>
          <span class="quotet2 text-bolder text-10">{{
            item.currency_name + "/" + item.legal_name
          }}</span>
        </div>
        <div class=" text-10 quotet2 mb-2 family-d text-medium text-right ">
          <span
            >{{
              $currency(
                decimalDigitsInputFilter(item.close_price, item.price_accuracy)
              )
            }}
            {{ item.legal_name }}</span
          >
        </div>
        <div class="text-right w-25 text-10 quotet3 text-medium ">
          <div :class="item.increase <= 0 ? 'text-red' : 'text-green'">
            {{ decimalDigitsInputFilter(item.increase * 100, 2) }}%
          </div>
        </div>
      </div>
    </div>
    <!-- websocket -->
    <!-- <Websocket
      :timeout="3000"
      name="涨幅"
      socket_type="RANKING"
      @change="onMessage"
    /> -->
  </div>
</template>

<script>
import {
  reactive,
  onMounted,
  getCurrentInstance,
  onBeforeUnmount,
  watch,
  ref,
  computed,
} from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import { numSort } from "@/utils/common";
// import Websocket from "@/components/websocket/WebSocket";
import { decimalDigitsInputFilter } from "@/utils/common";
import { deleteUserCurrencyMatch, addUserCurrencyMatch } from "@/api/currency";
import getMetaverse from "@/commonapi/metaverse";
import getNFT from "@/commonapi/nft";
import UseSystemSetting from "@/commonapi/useSystemSetting";

import { useI18n } from "vue-i18n";

export default {
  name: "Trading",
  // components: { Websocket },
  props: { tradingList: Array, secondMessage: Object },
  emits: ["changeNowdata", "getList"],
  setup(props, { emit }) {
    const $store = useStore();
    const { t } = useI18n();
    const tabActive = ref($store.state.user.secondtradingtab);
    const state = reactive({
      timer: null,
      tradList: [...props.tradingList],
      copytradList: [...props.tradingList],
      param: {
        currency_match_type: 2,
      },
      loading: false,
      sortParam: { close_price: "", transaction_amount: "" },
      curencyname: "",
      secondMessage: props.secondMessage,
      tabList: [
        { id: 1, name: t("exchange.selfSelect") },
        { id: 7, name: t("exchange.hold") },
        { id: 2, name: "USDT" },
        { id: 3, name: t("universe.universe") },
        { id: 4, name: "NFT" },
        { id: 5, name: "JPY" },
        { id: 6, name: "USD" },
      ],
    });
    const {
      appContext: {
        app: {
          config: { globalProperties },
        },
      },
    } = getCurrentInstance();
    const { $websocketTool } = globalProperties;
     // 获取开关状态
     const { virtual_wallet } = UseSystemSetting();
    watch(
      () => props.secondMessage,
      (newValue) => {
        onMessage(newValue);
      }
    );
    watch(
      () => props.tradingList,
      (newValue) => {
        state.tradList = [...newValue];
        state.copytradList = [...newValue];
      }
    );
    const metaverse = computed(() => {
      return $store.state.exchange.metaverseStatus;
    });
    const NFTtype = computed(() => {
      return $store.state.exchange.NFTStatus;
    });
    onMounted(() => {
      if ($store.state.user.secondtradingtab) {
        let tabIndex = state.tabList.findIndex((ele) => {
          return ele.id === $store.state.user.secondtradingtab;
        });
        if (tabIndex / 3 > 1) {
          scrollCount.value = Math.floor(tabIndex / 3) - 1;
          tabsClickScroll("right");
        }
        console.log(tabIndex, scrollCount.value);
      }
      metaverseStatus();
      NFTStatus();
    });
    //获取元宇宙显示状态
    const { metaverseStatus } = getMetaverse();
    const { NFTStatus } = getNFT();
    const handleMsg = () => {
      $websocketTool?.ws.send(
        JSON.stringify({
          socket_type:virtual_wallet.value ? "DEMO_RANKING" : "RANKING",
          subscribed: 1,
        })
      );
      $websocketTool.ws.onmessage = function(res) {
        const message = JSON.parse(res.data);
        if (message.type === (virtual_wallet.value ? "DEMO_RANKING" : "RANKING")) {
          onMessage(message);
        }
      };
    };
    const closeMsg = (msg) => {
      if ($websocketTool?.ws && $websocketTool.ws.readyState == 1) {
        $websocketTool?.ws.send(JSON.stringify(msg));
      }
    };
    const tabsRef = ref();
    const changeTab = (i, index) => {
      tabActive.value = i;
      tabActiveIndex.value = index;
      $store.commit("user/SET_TRADING_TAB_SEC", { active: i });
      emit("getList");
    };
    const isShowRight = computed(() => {
      const res = scrollCount.value * 150 + 240 < tabsRef.value?.scrollWidth;
      console.log(res);
      return res;
    });
    const tabActiveIndex = ref(0);
    const scrollCount = ref(0);
    const tabsClickScroll = (type) => {
      if (type === "left") {
        scrollCount.value -= 1;
      } else {
        const res = scrollCount.value * 150 + 240 < tabsRef.value?.scrollWidth;
        if (res) {
          scrollCount.value += 1;
        }
      }
      tabsRef.value.scrollLeft = scrollCount.value * 150;
    };
    // 更换自选
    const changeadd = (id, ischeck) => {
      const requestfun = ischeck
        ? deleteUserCurrencyMatch
        : addUserCurrencyMatch;
      state.loading = true;
      requestfun({ currency_match_id: id, currency_match_type: 3 })
        .then((res) => {
          state.loading = false;
          if (res.code === 200) {
            emit("getList");
          }
        })
        .catch((err) => {
          state.loading = false;
          ElMessage.error(err.message);
        });
    };
    // 查询交易对
    const search = () => {
      let array = state.copytradList.filter((item) => {
        return item.currency_name.indexOf(state.curencyname) > -1;
      });
      let issort = false;
      for (let i in state.sortParam) {
        if (state.sortParam[i] != "") {
          issort = true;
          state.tradList = numSort(state.sortParam[i], array, i);
        }
      }
      if (!issort) {
        state.tradList = array;
      }
    };
    // 改变排序
    const changeSort = (obj, type) => {
      for (let i in state.sortParam) {
        state.sortParam[i] = "";
      }
      state.sortParam[obj] = type;
      state.tradList = numSort(type, state.tradList, obj);
    };
    // websocket推送数据
    const onMessage = (val) => {
      let data = state.tradList;
      data.forEach((item) => {
        if (item.id === val.currencyMatchId) {
          item.increase = val.increaseData.increaseValue;
          item.close_price = val.increaseData.nowPrice;
        }
      });
      for (let i in state.sortParam) {
        if (state.sortParam[i] != "") {
          data = numSort(state.sortParam[i], data, i);
        }
      }
      state.tradList = data;
    };

    // 更换交易对
    const changeTrading = (item) => {
      const param = {
        currency_match_type: 3,
        currency_match_id: item.id,
      };
      $store.dispatch("exchange/gettradingDetail", param).then((data) => {
        $store.commit("exchange/SET_SECOND", data);
        const nowData = {
          highPrice: data.high_price,
          increaseValue: data.increase,
          lowPrice: data.low_price,
          nowPrice: data.close_price,
          transactionAmount: data.transaction_amount,
        };
        emit("changeNowdata", nowData);
      });
    };
    onBeforeUnmount(() => {});
    return {
      state,
      changeTrading,
      changeSort,
      search,
      onMessage,
      decimalDigitsInputFilter,
      handleMsg,
      closeMsg,
      tabActive,
      changeTab,
      changeadd,
      metaverse,
      metaverseStatus,
      NFTtype,
      NFTStatus,
      tabsRef,
      tabsClickScroll,
      tabActiveIndex,
      scrollCount,
      isShowRight,
    };
  },
};
</script>

<style scoped lang="less">
.trad-box {
  z-index: 1;
  .over-tab {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 55px;
    padding: 0px 10px;
  }
}
.trad-tabbox {
  width: 100%;
  padding: 10px 0;
  border-bottom: 1px solid;
  overflow-y: hidden;
  overflow-x: scroll;
}
.trad-tab {
  min-height: 34px;
  line-height: 34px;
  position: relative;
  margin-inline-end: 40px;
  flex-shrink: 0;
}
.mb-6 {
  margin-bottom: 6px;
}
.mb-2 {
  margin-bottom: 2px;
}
.mb-10 {
  margin-bottom: 10px;
}
.mb-20 {
  margin-bottom: 20px;
}
.ml-10 {
  margin-inline-start: 10px;
}
.trad {
  box-sizing: border-box;
  margin-bottom: 14px;
  position: relative;
  line-height: 22px;
  height: 20px;
}
.trad-all {
  width: 100%;
  overflow-y: scroll;
  height: 400px;
  padding: 2px 10px;
}
.box {
  padding: 10px;
  box-sizing: border-box;
}
// 搜索框
.search {
  width: 100%;
  height: 24px;
}
.sort {
  width: 100%;
  height: 19px;
}
.sort-icon {
  height: 100%;
  i {
    height: 5px;
  }
}
.w-33 {
  width: 30%;
}
.w-25 {
  width: 25%;
}
.text-22 {
  font-size: 22px;
  margin-inline-start: -1px;
}
.w-25 {
  width: 25%;
}
</style>
